//
//  PhotosInAlbumFBViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 8/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PhotosInAlbumFBViewController.h"
#import "PhotoSource.h" 
#import "AppDelegate.h"
#import "Photo.h"
#import "Request.h"
#import "User.h"

@implementation PhotosInAlbumFBViewController

@synthesize albumID,images,navController,albumVC,albumName;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(void) backPressed 
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)setTitle:(NSString*)title
{       
    UILabel * label = [[[UILabel alloc] initWithFrame:CGRectMake(0,0,320,43)] autorelease];
	label.textColor = [UIColor blackColor];
	//[label setFont:[UIFont boldSystemFontOfSize:26]];
	label.backgroundColor = [UIColor clearColor]; 
	label.text = title;
    label.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
	self.navigationItem.titleView = label;
	[label sizeToFit];    
}

-(void)initNavigationBar 
{
    self.navigationController.navigationBar.hidden = NO;
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    UIView *overlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 320, 1)];
    [overlayView setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar addSubview:overlayView]; // navBar is your UINavigationBar instance
    [overlayView release];
    
    UIButton *BtnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    BtnBack.frame = CGRectMake(0, 0, 29, 29);
    [BtnBack setImage:[UIImage imageNamed:@"back-button.png"] forState:UIControlStateNormal];
    [BtnBack addTarget:self action:@selector(backPressed) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:BtnBack];
    self.navigationItem.leftBarButtonItem =backItem;
    [backItem release];
    
    [self.tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]]; 
}

// viewWillAppear and updateTableLayout function follow to fix bug: the space appear at top Album View

- (void) updateTableLayout {
	
	self.tableView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
	self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(TTBarsHeight(), 0, 0, 0);
}

-(void) uploadPhoto:(MBProgressHUD*)progress
{      
    [[AppDelegate shareDelegate]hideLoadingView];
    
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myurl]];
    UIImage *imageData = [[UIImage alloc] initWithData:data];
    NSError *error = nil;
        
    NSData *avatarData = UIImagePNGRepresentation(imageData);
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    
    [JGoAPI uploadPhotoWithUserId:userId avatarData:avatarData error:&error];
    
    if (!error) {
        [self.navigationController popToViewController:self.albumVC animated:YES];
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
}
- (void)thumbsTableViewCell:(TTThumbsTableViewCell*)cell didSelectPhoto:(id<TTPhoto>)photo 
{
    [[AppDelegate shareDelegate] hideLoadingView];
    myurl = [photo URLForVersion:TTPhotoVersionThumbnail]; 
    NSLog(@"%@",myurl);    
    
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Uploading Photo..." 
                          selector:@selector(uploadPhoto:)];
}

#pragma mark - FB Delegete

- (void) readFacebookData {
    
    NSString *path = [NSString stringWithFormat:@"%@/photos?limit=0",albumID];
     NSLog(@"%@",path);
    [[[AppDelegate shareDelegate]facebook] requestWithGraphPath:path andDelegate:(id)self];
}

- (void)request:(FBRequest *)request didLoad:(id)result 
{
    //the results from facebook
    NSLog(@"%@",result);
    NSArray *photoAlbumArray = [[NSArray alloc]init];
    photoAlbumArray = (NSArray*)[result valueForKey:@"data"];
    
    for (NSDictionary *obj in photoAlbumArray) {
             
        NSLog(@"%@",obj);
        if (![[obj objectForKey:@"source"] isKindOfClass:[NSNull class]]) {
            NSString *url  = [obj objectForKey:@"source"];
            NSLog(@"Image URL: %@",url);
            CGSize imgSize =  CGSizeMake(320, 460);
            if (![[obj objectForKey:@"width"] isKindOfClass:[NSNull class]]) {
                imgSize.width = [[obj objectForKey:@"width"]floatValue];
            }
            if (![[obj objectForKey:@"height"] isKindOfClass:[NSNull class]]) {
                imgSize.height = [[obj objectForKey:@"height"]floatValue];
            }
            [images addObject: [[[Photo alloc] initWithURL:url
                                                  smallURL:url  
                                                      size:imgSize] autorelease]];
        }
    }
   
    self.photoSource = [[PhotoSource alloc]  
                        initWithType:PhotoSourceNormal  
                        title:albumName  
                        photos:images  
                        photos2:nil  
                        ];
    [self.tableView reloadData];
    [[AppDelegate shareDelegate]hideLoadingView];
}



- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"Err message: %@", [[error userInfo] objectForKey:@"error_msg"]);
    NSLog(@"Err code: %d", [error code]);
    [[AppDelegate shareDelegate]hideLoadingView];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                    message:[[error userInfo] objectForKey:@"error_msg"] 
                                                   delegate:self 
                                          cancelButtonTitle:@"OK" 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

#pragma mark - View lifecycle
-(void)createPhotos {
    /*
    images = [[NSMutableArray alloc] initWithCapacity:[images count]];
    
    for (user_image *img in self.photos) {
        NSString *url  = [NSString stringWithFormat:kBaseURL,img.image];
        NSLog(@"Image URL: %@",url);
        
        [images addObject: [[[Photo alloc] initWithURL:url
                                              smallURL:@"bundle://img_avatar.png"
                                                  size:CGSizeMake(320, 460)] autorelease]];
        
    }
     
    */
}
-(void)viewWillAppear:(BOOL)animated {
	images = [[NSMutableArray alloc] init];
    [[AppDelegate shareDelegate]showLoadingView];
    [self readFacebookData];
	[super viewWillAppear:animated];
    [self initNavigationBar];
    [self setTitle:albumName];
	//UINavigationController* navControllerAlbum = self.navController;
	//navControllerAlbum.navigationBar.barStyle = UIBarStyleBlackOpaque;
	
	[self setWantsFullScreenLayout:YES];
	
}

- (void)viewDidLoad {
    	        	
} 

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    
    [images release];
    
    self.navController = nil;
    [super dealloc];
}


@end
